package com.lagou.web;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class Filter implements javax.servlet.Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        HttpSession session = req.getSession();
        Cookie[] cookies = req.getCookies();
        String username = null;
        String password = null;

        //获取cookies中的用户名和密码
        for(Cookie cookie : cookies){
            if ("username".equals(cookie.getName())){
                username = cookie.getValue();
            }
            if ("password".equals(cookie.getName())){
                password = cookie.getValue();
            }
        }

        // 先判断session中是否存有用户名和密码即是否成功登录过
        // 再判断cookie中的用户名密码是否与session一致
        if (session.getAttribute("username") != null && session.getAttribute("password") != null){
            if (session.getAttribute("username").equals(username) && session.getAttribute("password").equals(password)){
                filterChain.doFilter(req,resp);
            }else{
                resp.sendRedirect("http://localhost:63342/stage2_module3_homework/web/logIn.html");
            }
        }else{
            resp.sendRedirect("http://localhost:63342/stage2_module3_homework/web/logIn.html");
        }

    }

    @Override
    public void destroy() {

    }
}
